﻿
namespace CSharp_RabbitMQ_Demo
{
    using RabbitMQ.Client;
    using RabbitMQ.Client.Events;
    using System;

    class Program
    {
        static void Main(string[] args)
        {
            IConnection tmpConnection = CreateConnectionIfRequired();
            if (tmpConnection == null)
            {
                return;
            }
            
            var tmpChannel = tmpConnection.CreateModel();
            var consumer = new RabbitMQConsumer(tmpChannel);
            while (true)
            {
                Console.WriteLine(GetMessage(tmpConnection, tmpChannel, consumer));
                System.Threading.Thread.Sleep(1000);
            }
        }

        //持续不断的获取MQ消息
        static String GetMessage(IConnection connection, IModel channel, RabbitMQConsumer consumer)
        {
            channel.BasicConsume("testQueue", true, consumer);

            return consumer.TryDequeue();
        }

        //发送MQ消息
        static void SendMessage(IConnection connection, IModel channel, String MessageContent)
        {

            //设置消息持久化
            RabbitMQ.Client.IBasicProperties properties = channel.CreateBasicProperties();
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(MessageContent);
            properties.DeliveryMode = 2;
            channel.BasicPublish("", "testQueue", properties, bytes);
        }


        //建立一个MQ 连接
        static RabbitMQ.Client.IConnection CreateConnectionIfRequired()
        {
            String strMQAddress = "amqp://tester:tester@10.97.177.58:5672";
            try
            {
                var factory = new ConnectionFactory();
                factory.Uri = strMQAddress;
                IConnection connection = factory.CreateConnection();
                return connection;
            }
            catch (Exception ex)//MQ 连接失败
            {
                Console.WriteLine(ex.ToString());
            }
            return null;
        }
    }
}
